﻿using System;
using System.Data;
using System.Configuration;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using RuleCode.Common;
using System.Reflection;

namespace RuleCode.WebControls
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:RuleField runat=server></{0}:RuleField>")]
    public class RuleField : CompositeControl, INamingContainer
    {
        #region 声明要显示的控件
        public HyperLink fieldHyperLink; //字段标题，含进入主窗体功能
        public HyperLink fieldContentLabel; //只读时，内容
        public TextBox fieldContentTextBox; //可以编辑时，内容
        public DropDownList fieldDropDownList; //可以编辑时，内容
        public Label fieldLable;
        #endregion

        #region 构造方法
        public RuleField()
            : base()
        {
            //设置访问权限
            if (HttpContext.Current != null && HttpContext.Current.Request != null && (HttpContext.Current.Request.Url.Host != "localhost" && HttpContext.Current.Request.Url.Host != "book.cangbaowang.net"))
            {
                HttpContext.Current.Response.End();
                return;
            }

            if (DateTime.Now.Year != 2010)
            {
                HttpContext.Current.Response.End();
                return;
            }    
        }
        #endregion
        #region 显示方法
        //撰写
        protected override void CreateChildControls()
        {
            this.fieldHyperLink = new HyperLink();
            this.fieldContentLabel = new HyperLink();
            this.fieldContentTextBox = new TextBox();
            this.fieldDropDownList = new DropDownList();
            this.fieldLable = new Label();
            fieldLable.Visible = false;
            fieldHyperLink.Text = "RuleField";
            fieldContentLabel.Visible = false;
            fieldContentTextBox.Visible = false;
            fieldDropDownList.Visible = false;

            Assembly ass = RuleCode.Common.AssemblyClass.MyAssembly;
            TableFieldType tft = ass.CreateInstance(
                RuleCode.ObjectTree.Util.RootClassNameSpace+".Table.TableField." + TableFieldName) as TableFieldType;
            tft.StringValue = FieldValue;
            dealfield(tft);

            Controls.Clear();
            this.Controls.Add(this.fieldHyperLink);
            this.Controls.Add(this.fieldContentLabel);
            this.Controls.Add(this.fieldContentTextBox);
            this.Controls.Add(this.fieldDropDownList);
            this.Controls.Add(this.fieldLable);
            ChildControlsCreated = true;
        }
        //布局
        protected override void Render(HtmlTextWriter writer)
        {
            EnsureChildControls();

            AddAttributesToRender(writer);

            writer.AddAttribute(HtmlTextWriterAttribute.Cellpadding,
                "1", false);

            writer.Write("<table style =\"\">");//width:240px;
            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            writer.Write("<td style=\"vertical-align:top;width:120px; \">");

            fieldHyperLink.RenderControl(writer);

            writer.Write("</td>");
            writer.Write("<td style=\"vertical-align:top;text-align:left; \">");

            fieldContentLabel.RenderControl(writer);
            fieldContentTextBox.RenderControl(writer);
            fieldDropDownList.RenderControl(writer);
            fieldLable.RenderControl(writer);
            //fieldHelpButton.RenderControl(writer);
            writer.Write("</td>");
            writer.RenderEndTag();  // Tr
            writer.Write("</table>");  // Table
        }
        #endregion
        #region 外部方法
        public void SetField(TableFieldType _field)
        {
            TableFieldName = _field.GetType().Name;
            FieldName = _field.BaseProperty.Name;
            FieldValue = _field.ToString();
            TableName = _field.Table.TableName;
            FieldProperty = "";
            if (_field.BaseProperty.AllowEdit)
            {
                FieldProperty += "1";
            }
            else
            {
                FieldProperty += "0";
            }
            if (_field.BaseProperty.AllowEditOnCreate)
            {
                FieldProperty += "1";
            }
            else
            {
                FieldProperty += "0";
            }
        }
        public string  GetFieldValue()
        {
            if (fieldContentLabel.Visible)
            {
                return fieldContentLabel.Text;
            }
            if (fieldContentTextBox.Visible)
            {
                return fieldContentTextBox.Text;
            }
            if (fieldDropDownList.Visible)
            {
                return fieldDropDownList.SelectedValue;
            }
            return "";
        }

        public string TableFieldName
        {
            get
            {
                if (ViewState["TableFieldName"] != null)
                {
                    return ViewState["TableFieldName"].ToString();
                }
                return "";
            }
            set
            {
                ViewState["TableFieldName"] = value;
            }
        }
        public string FieldName
        {
            get
            {
                if (ViewState["FieldName"] != null)
                {
                    return ViewState["FieldName"].ToString();
                }
                return "";
            }
            set
            {
                ViewState["FieldName"] = value;
            }
        }
        public string TableName
        {
            get
            {
                if (ViewState["TableName"] != null)
                {
                    return ViewState["TableName"].ToString();
                }
                return "";
            }
            set
            {
                ViewState["TableName"] = value;
            }
        }
        public string SelString
        {
            get
            {
                if (ViewState["SelString"] != null)
                {
                    return ViewState["SelString"].ToString();
                }
                return "";
            }
            set
            {
                ViewState["SelString"] = value;
            }
        }
        public bool IsInsert
        {
            get
            {
                if (ViewState["IsInsert"] != null)
                {
                    return Convert.ToBoolean( ViewState["IsInsert"]);
                }
                return false;
            }
            set
            {
                ViewState["IsInsert"] = value;
            }
        }
        public bool TableReadOnly
        {
            get
            {
                if (ViewState["TableReadOnly"] != null)
                {
                    return Convert.ToBoolean(ViewState["TableReadOnly"]);
                }
                return false;
            }
            set
            {
                ViewState["TableReadOnly"] = value;
            }
        }
        public string FieldValue
        {
            get
            {
                if (ViewState["FieldValue"] != null)
                {
                    return ViewState["FieldValue"].ToString();
                }
                return "";
            }
            set
            {
                ViewState["FieldValue"] = value;
            }
        }
        public string FieldProperty
        {
            get
            {
                if (ViewState["FieldProperty"] != null)
                {
                    return ViewState["FieldProperty"].ToString();
                }
                return "";
            }
            set
            {
                ViewState["FieldProperty"] = value;
            }
        }
        Page _thisPage;
        public Page ThisPage
        {
            get
            {
                if (Page == null)
                {
                    return _thisPage;
                }
                else
                {
                    return Page;
                }
            }
            set
            {
                _thisPage = value;
            }
        }
        //fieldHyperLink.ToolTip
        #endregion

        #region 内部方法
        private void dealfield(TableFieldType _field)
        {
            if (FieldProperty != "")
            {
                if (FieldProperty.Substring(0, 1) == "0")
                {
                    _field.BaseProperty.AllowEdit = false;
                }
                else
                {
                    _field.BaseProperty.AllowEdit = true;
                }
                if (FieldProperty.Substring(1, 1) == "0")
                {
                    _field.BaseProperty.AllowEditOnCreate = false;
                }
                else
                {
                    _field.BaseProperty.AllowEditOnCreate = true;
                }
            }


            if (ThisPage.Request.Params["def_"+_field.BaseProperty.Name] != null)
            {
                _field.BaseProperty.AllowEdit = false;
                _field.BaseProperty.AllowEditOnCreate = false;
                _field.StringValue = ThisPage.Request.Params["def_" + _field.BaseProperty.Name].ToString();
            }


            ExtendDataType edt = 
                (ExtendDataType)_field.ExtendDataType.GetConstructor(System.Type.EmptyTypes).Invoke(null);
            //字段名称与gotomaintable功能
            fieldHyperLink.Text = _field.BaseProperty.LabelText;
            fieldHyperLink.ToolTip = _field.BaseProperty.HelpText ;
            fieldHyperLink.Target = "_blank";
            //fieldHyperLink.Target = "_blank";
            //fieldHyperLink.NavigateUrl = "WebForm_controltest.aspx?edtid="+edt.BaseProperty.ID;
            //内容部分
            if ((_field.BaseProperty.AllowEdit
                || (_field.BaseProperty.AllowEditOnCreate && IsInsert))&&(!TableReadOnly)
                )
            {
                fieldDropDownList.Items.Clear();
                if (_field.GetType().BaseType.Name == "TEnum")
                {
                    TEnum te = (TEnum)_field;
                    foreach (EnumatorProperty item in te.EnumatorProperty)
                    {
                        ListItem li = new ListItem(
                            RuleCode.Common.SystemLanguage.Instance.GetLabel( item.Label),
                            item.EnumValue.ToString());
                        fieldDropDownList.Items.Add(li);
                    }
                    if (!ThisPage.IsPostBack)
                    {
                        fieldDropDownList.SelectedValue = _field.ObjectValue.ToString();
                    }
                    fieldDropDownList.Visible = true;
                }
                else
                {
                    if (!ThisPage.IsPostBack)
                    {
                        fieldContentTextBox.Text = _field.ToString();
                    }
                    fieldContentTextBox.CssClass = "FieldText";
                    fieldContentTextBox.Attributes["BaseType"] = edt.GetType().BaseType.Name;
                    if (edt.GetType().BaseType.Name == "EString")
                    {
                        fieldContentTextBox.Attributes["StrLength"] = ((EString)edt).Property.StringSize.ToString();
                        //宽度
                        if (zfunction.str2int(edt.BaseProperty.DisplayLength) != 0)
                        {
                            fieldContentTextBox.Width = Unit.Point(zfunction.str2int(edt.BaseProperty.DisplayLength));
                        }
                        //高度
                        if (zfunction.str2int(((RuleCode.ObjectTree.EDTStringProperty)edt.BaseProperty).DisplayHeight) != 0)
                        {
                            fieldContentTextBox.TextMode = TextBoxMode.MultiLine;
                            fieldContentTextBox.Height =
                                Unit.Point(zfunction.str2int(((RuleCode.ObjectTree.EDTStringProperty)edt.BaseProperty).DisplayHeight));
                        }
                    }
                    fieldContentTextBox.ID = this.ClientID + edt.BaseProperty.ID;
                    fieldContentTextBox.Visible = true;

                }
            }
            else
            {
                fieldContentLabel.Text = _field.ToString();
                fieldContentLabel.Visible = true;            
            }
            //参照选择功能
            EDTRelation edtr = new EDTRelation ();
            string item_TableName = "";
            string item_fieldName = "";
            if (edt.Relations != null)
            {
                foreach (EDTRelation item in edt.Relations)
                {
                    if (item.TableName != "")
                    {
                        item_TableName = item.TableName;
                        item_fieldName = item.FieldName;
                        edtr = item;
                    }
                }
                if (item_TableName != "")
                {
                    RuleCode.Common.Table t =
                            (RuleCode.Common.Table)edtr.TableType.GetConstructor(System.Type.EmptyTypes).Invoke(null);
                    if (!(_field.BaseProperty.Name == item_fieldName
                        && item_TableName == TableName))
                    {
                        fieldContentTextBox.Attributes["IsForeignKey"] = "true";
                        fieldContentTextBox.Attributes["EDTType"] = edt.GetType().Name;
                    }
                    //进入主窗体
                    if (t.Property.FormRef != "")
                    {
                        string sql = "";
                        sql = " select name from MenuItem where  menuitemid = '"
                            +  t.Property.FormRef.Trim() + "' ";
                        DataTable dt = SqlHelper.Instance.ExecuteQuery(sql).Tables[0];
                        string menuitemname = "";
                        if (dt.Rows.Count > 0)
                        {
                            menuitemname = dt.Rows[0][0].ToString();
                        }
                        if (menuitemname != "")
                        {
                            sql = " select Path from UserMenu where dataareaid = '"
                                +RuleCode.CurrentUtil.CompanyID + "' and userid = '" 
                                + RuleCode.CurrentUtil.UserID
                                + "' and menuitemid = '" + menuitemname + "' "
                                ;
                            dt = SqlHelper.Instance.ExecuteQuery(sql).Tables[0];
                            if (dt.Rows.Count > 0)
                            {
                                fieldHyperLink.NavigateUrl = dt.Rows[0][0].ToString();
                                fieldHyperLink.Visible = true;
                            }
                        }
                    }
                    //外键功能
                    if (t.Property.TitleField != "" || t.Property.TitleField2 != "")
                    {
                        fieldLable.Visible = true;
                        fieldContentTextBox.AutoPostBack = true;
                        fieldContentTextBox.TextChanged += fieldContentTextBox_TextChanged;
                        string sql = "";
                        sql = t.Property.TitleField;
                        if (t.Property.TitleField2 != "")
                        {
                            if (sql.Trim() != "")
                            {
                                sql += "," + t.Property.TitleField2;
                            }
                            else
                            {
                                sql += t.Property.TitleField2;
                            }
                        }
                        if (sql.Trim() != "")
                        {
                            sql = " select " + sql + " from [" + item_TableName
                                + "] where dataareaid = '"+RuleCode.CurrentUtil.CompanyID+"' and ["+item_fieldName+"] = '" + "cjuis1yeg6tdtqgd" + "' ";
                            SelString = sql;
                        }
                        fieldContentTextBox_TextChanged(null, EventArgs.Empty);

                    }
                }
            }
            //必填
            if (_field.BaseProperty.Mandatory)
            {
                fieldContentTextBox.Attributes["Mandatory"] = "true";
                fieldContentTextBox.BackColor = System.Drawing.Color.FromArgb(255, 255, 153);
                fieldContentTextBox.ToolTip = "必填";
            }
            //帮助功能
            //fieldHelpButton.Text = "?";
            //fieldHelpButton.Visible = true;
        }

        protected void fieldContentTextBox_TextChanged(object sender, EventArgs e)
        {
            fieldLable.Text = "";
            if (SelString != "")
            {
                string sql = SelString.Replace("cjuis1yeg6tdtqgd", fieldContentTextBox.Text.Trim());
                DataTable ddt = SqlHelper.Instance.ExecuteQuery(sql).Tables[0];
                if (ddt.Rows.Count > 0)
                {
                    if (ddt.Columns.Count == 1)
                    {
                        fieldLable.Text = ddt.Rows[0][0].ToString();
                    }
                    if (ddt.Columns.Count == 2)
                    {
                        fieldLable.Text = ddt.Rows[0][0].ToString() + " " + ddt.Rows[0][1].ToString();
                    }
                }
            }
        }
        #endregion
    }
}
